<template>
  <div class="flex w-full h-full bg-white text-[#000000ba]">
    <div
      class="w-[20%] flex items-center justify-center border-r-[1px] border-r-[#ccc]"
    >
      <div class="flex flex-col items-center">
        <el-upload
          class="avatar-uploader"
          ref="resUpload"
          :action="uploadUrl"
          :show-file-list="false"
          :limit="1"
          :data="requestData"
          :headers="headers"
          :accept="accept"
          :disabled="!modifyDisabled"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="userInfoForm?.photoPath"
            :src="userInfoForm?.photoPath"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <p class="leading-[60px] text-[24px]">
          姓名：{{ userInfoForm.emplyName }}
        </p>
        <p class="leading-[60px] text-[24px]">
          号码：{{ userInfoForm.mobileNum }}
        </p>
        <p class="leading-[60px] text-[24px]">
          公司：{{ userInfoForm.groupOrgName }}
        </p>
      </div>
    </div>
    <div class="w-[80%] p-5">
      <el-form
        ref="userInfoFormRef"
        :model="userInfoForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
        :disabled="!modifyDisabled"
        :hide-required-asterisk="hideRequiredAsterisk"
      >
        <el-form-item label="姓名：" prop="emplyName">
          <el-input v-model="userInfoForm.emplyName" />
        </el-form-item>
        <el-form-item label="性别：" prop="gender">
          <el-select v-model="userInfoForm.gender" placeholder="请选择性别">
            <el-option :key="1" label="男" :value="1" />
            <el-option :key="2" label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号：" prop="mobileNum">
          <el-input v-model="userInfoForm.mobileNum" />
        </el-form-item>
        <el-form-item label="身份证号：" prop="idNo">
          <el-input v-model="userInfoForm.idNo" />
        </el-form-item>
        <el-form-item label="工号：" prop="emplyJobNum">
          <el-input v-model="userInfoForm.emplyJobNum" />
        </el-form-item>
        <el-form-item label="排序号：">
          <el-input-number
            class="w-full"
            :controls="false"
            v-model="userInfoForm.sort"
            :min="0"
            :max="99999999"
            :value-on-clear="null"
          />
        </el-form-item>
        <el-form-item label="出生日期：" prop="birthDate">
          <el-input v-model="userInfoForm.birthDate" />
        </el-form-item>
        <el-form-item label="入职日期：" prop="entryDate">
          <el-input disabled v-model="userInfoForm.entryDate" />
        </el-form-item>
        <el-form-item label="公司/部门：" prop="superOrgName">
          <el-input disabled v-model="userInfoForm.superOrgName" />
        </el-form-item>
        <el-form-item label="岗位信息：" prop="postList">
          <el-input disabled v-model="userInfoForm.post" />
        </el-form-item>
        <el-form-item label="所属群组：" prop="comuseGroupList">
          <el-input disabled v-model="userInfoForm.comuse" />
        </el-form-item>
        <el-form-item label="所属角色：" prop="roleList">
          <el-input disabled v-model="userInfoForm.role" />
        </el-form-item>
        <el-form-item label="签名图片：" prop="emplySignature">
          <el-upload
            class="siginUpload max-w-[400px]"
            action=""
            :show-file-list="false"
            :on-change="handleSiginChange"
            accept=".jpg, .png, .bmp"
            :auto-upload="false"
          >
            <el-image v-if="imageSiginUrl" :src="imageSiginUrl" />
            <el-image
              v-else-if="userInfoForm.emplySignature"
              :src="userInfoForm.emplySignature"
            />
            <i v-else class="iconfont icon-jiahao" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="w-full h-10 flex items-center justify-center">
        <el-button class="w-[200px]" @click="resetForm">返回</el-button>
        <el-button
          class="w-[200px]"
          v-if="!modifyDisabled"
          type="primary"
          @click="modifyForm"
        >
          修改信息
        </el-button>
        <el-button
          class="w-[200px]"
          v-if="modifyDisabled"
          type="primary"
          @click="submitForm(userInfoFormRef)"
        >
          保存
        </el-button>
        <el-button v-if="modifyDisabled" class="w-[200px]" @click="noModifyForm"
          >取消修改</el-button
        >
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import { User } from "@/types/user";
import { _getUser, _getOrgGroupemplychange } from "@/api/user";
import { ElMessage } from "element-plus";
import type { UploadProps } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import store from "@/store";
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
import router from "@/router";
import * as _ from "lodash";
import { checkPsidno, telRules } from "@/utils/rules";

const userInfoForm = ref<User>({
  belongOrganizationId: "",
  birthDate: "",
  comuseGroupList: [],
  currentOrgPostList: [],
  defaultCheckOrgId: "",
  empLeaderNames: "",
  emplyId: "",
  emplyJobNum: "",
  emplyName: "",
  emplySignature: "",
  entryDate: "",
  forbidDate: "",
  gender: null,
  groupOrgName: "",
  idNo: "",
  imagePostId: "",
  imagePostName: "",
  imagePostSuperOrgId: "",
  leaderList: [],
  leaderListName: "",
  mobileNum: "",
  orgType: null,
  otherOrgPostList: [],
  photoPath: "",
  postId: "",
  postList: [],
  postName: "",
  postSuperOrgId: "",
  roleList: [],
  rootOrgId: "",
  sort: null,
  superAllOrgId: "",
  superAllOrgName: "",
  superOrg: [],
  superOrgId: "",
  superOrgName: "",
});
const modifyDisabled = ref<boolean>(false);
const userInfoFormRef = ref<FormInstance>();
// 修改保存
async function submitForm(formEl: FormInstance | undefined) {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const reg: any = /^1\d{10}$/;
      console.log(
        telRules(userInfoForm.value.mobileNum),
        checkPsidno(userInfoForm.value.idNo)
      );

      if (!telRules(userInfoForm.value.mobileNum)) {
        ElMessage.warning("请输入正确的手机号");
        return;
      }
      if (!checkPsidno(userInfoForm.value.idNo)) {
        ElMessage.warning("请输入正确的身份证号");
        return;
      }
      let data: any = {
        emplyName: userInfoForm.value.emplyName,
        gender: userInfoForm.value.gender ?? null,
        idNo: !!userInfoForm.value.idNo ? userInfoForm.value.idNo : null,
        postId: userInfoForm.value.postId,
        mobileNum: userInfoForm.value.mobileNum,
        sort: userInfoForm.value.sort ?? null,
        superOrgId: userInfoForm.value.superOrgId,
        emplyJobNum: userInfoForm.value?.emplyJobNum ?? null,
        emplyId: userInfoForm.value?.emplyId,
        emplySignature: userInfoForm.value.emplySignature ?? null,
        birthDate: userInfoForm.value?.birthDate,
        entryDate: userInfoForm.value?.entryDate,
        leaderList: userInfoForm.value?.leaderList,
        roleIdList: userInfoForm.value.roleList?.map((e) => e.orgId),
        postIdList: userInfoForm.value.roleList?.map((e) => e.orgId),
        comuseGroupIdList: userInfoForm.value.roleList?.map((e) => e.orgId),
      };
      const res: any = await _getOrgGroupemplychange(data);
      if (res?.code == 10000) {
        getUserInfo();
        modifyDisabled.value = false;
        hideRequiredAsterisk.value = true;
        ElMessage.success(res?.message ? res?.message : "修改成功！");
      } else {
        ElMessage.warning(res?.message ? res?.message : "修改失败！");
      }
    } else {
      ElMessage.warning("有必填项未填写！");
    }
  });
}
// 是否显示红色星号
const hideRequiredAsterisk = ref<boolean>(true);
// 修改信息
function modifyForm() {
  modifyDisabled.value = true;
  hideRequiredAsterisk.value = false;
}
// 取消修改
function noModifyForm() {
  modifyDisabled.value = false;
  hideRequiredAsterisk.value = true;
}
// 关闭返回首页
function resetForm() {
  router.replace("/");
}
// 头像上传地址
const uploadUrl =
  import.meta.env.VITE_BASE_URL + "/admin/system/system-file/upload";
// 头像上传额外参数
const { userInfo, tokenObj } = store.getters;
const requestData = {
  purpose: 2,
  actId: userInfo?.emplyId,
};
// 设置头像上传请求头参数
const headers = {
  Authorization: tokenObj?.tokenHead + "" + tokenObj?.token,
};
// 设置头像上传类型限制
const accept = ".JPG, .PNG, .JPEG, .PSD, .BMP";
// 签名上传
const imageSiginUrl = ref<string>();
function handleSiginChange(file: any, fileList: any) {
  const fileExt = file.name.substr(file.name.lastIndexOf(".") + 1);
  if (!["jpg", "png", "bmp"].includes(fileExt)) {
    ElMessage.error({
      message: "文件格式错误！",
    });
    return;
  }
  imageSiginUrl.value = URL.createObjectURL(file.raw);
  getBase64(file.raw).then((res: any) => {
    userInfoForm.value.emplySignature = res;
  });
}
//图片转码
function getBase64(file: any) {
  return new Promise(function (resolve, reject) {
    let reader: any = new FileReader();
    let imgResult = "";
    reader.readAsDataURL(file);
    reader.onload = function () {
      //全部采用png格式
      imgResult = reader.result.replace(
        /^data:image\/\w+;base64,/,
        "data:image/png;base64,"
      );
    };
    reader.onerror = function (error: any) {
      reject(error);
    };
    reader.onloadend = function () {
      resolve(imgResult);
    };
  });
}
// 获取数据
async function getUserInfo() {
  const res: any = await _getUser(userInfo?.emplyId);
  if (res?.code == 10000) {
    userInfoForm.value = res?.data;
    userInfoForm.value.roleList = _.uniqBy(res?.data.roleList, "orgId");
    userInfoForm.value.comuseGroupList = _.uniqBy(
      res?.data.comuseGroupList,
      "orgId"
    );
    userInfoForm.value.postList = _.uniqBy(res?.data.postList, "orgId");

    userInfoForm.value.role = userInfoForm.value?.roleList
      ?.map((e: any) => {
        return e.orgName;
      })
      ?.join("，");
    userInfoForm.value.comuse = userInfoForm.value?.comuseGroupList
      ?.map((e: any) => {
        return e.orgName;
      })
      ?.join("，");
    userInfoForm.value.post = userInfoForm.value?.postList
      ?.map((e: any) => {
        return e.orgName;
      })
      ?.join("，");
    store.commit("setUserInfo", res?.data);
  } else {
    ElMessage.warning(res?.message ? res?.message : "获取用户信息失败!");
  }
}
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  getUserInfo();
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.info("图片最大不可超过2MB!");
    return false;
  }
  return true;
};
onMounted(() => {
  getUserInfo();
});
const rules = reactive<FormRules<User>>({
  emplyName: [
    {
      required: true,
      message: "请输入姓名",
      trigger: ["blur", "change"],
    },
  ],
  gender: [
    {
      required: true,
      message: "请选择性别",
      trigger: ["blur", "change"],
    },
  ],
  mobileNum: [
    {
      required: true,
      message: "请输入手机号",
      trigger: ["blur", "change"],
    },
  ],
  idNo: [
    {
      required: true,
      message: "请输入身份证号",
      trigger: ["blur", "change"],
    },
  ],
  emplyJobNum: [
    {
      required: true,
      message: "请输入工号",
      trigger: ["blur", "change"],
    },
  ],
  birthDate: [
    {
      required: true,
      message: "请选择出生日期",
      trigger: ["blur", "change"],
    },
  ],
});
</script>

<style scoped>
.avatar-uploader {
  width: 70%;
  height: 70%;
  .avatar {
    width: 100%;
    height: 100%;
    display: block;
  }
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  text-align: center;
}
.el-input-number .el-input__inner {
  text-align: left;
}
</style>
